package com.ruoyi.pg.questionnaire.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.pg.answerSheet.domain.PgAnswer;
import com.ruoyi.pg.answerSheet.service.IPgAnswerService;
import com.ruoyi.pg.questionnaire.domain.PgQuestion;
import com.ruoyi.pg.questionnaire.vo.PgQuestionVo;
import com.ruoyi.pg.questionnaire.mapper.PgQuestionMapper;
import com.ruoyi.pg.questionnaire.service.IPgQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 问卷题目Service业务层处理
 *
 * @author Ming
 * @date 2025-08-22
 */
@Service
public class PgQuestionServiceImpl extends ServiceImpl<PgQuestionMapper, PgQuestion> implements IPgQuestionService {

    @Autowired
    private IPgAnswerService answerService;

    @Override
    public TableDataInfo<PgQuestionVo> queryList(PgQuestionVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<PgQuestionVo> queryAll(PgQuestionVo entity) {
        List<PgQuestionVo> pgQuestionVos = this.baseMapper.queryList(entity);
        for (PgQuestionVo pgQuestionVo : pgQuestionVos) {
            if (ObjectUtil.isNotEmpty(pgQuestionVo.getContent())) {
                pgQuestionVo.setOptionList(Arrays.asList(pgQuestionVo.getContent().split(",")));
            }
            PgAnswer pgAnswer = answerService.queryByIds(entity.getAssId(), pgQuestionVo.getId());
            if (ObjectUtil.isNotEmpty(pgAnswer)) {
                pgQuestionVo.setAnswer(pgAnswer.getContent());
                if (ObjectUtil.isNotEmpty(pgAnswer.getRemark())) pgQuestionVo.setAnswerRemark(pgAnswer.getRemark());
                if (pgQuestionVo.getQuestionType().equals("多选") && ObjectUtil.isNotEmpty(pgAnswer.getContent()))
                    pgQuestionVo.setCheckAnswer(pgAnswer.getContent().split(","));
                if (ObjectUtil.isNotEmpty(pgAnswer.getContent())) {
                    pgQuestionVo.setIfAnswer(true);
                } else {
                    pgQuestionVo.setIfAnswer(false);
                }
            }
        }
        return pgQuestionVos;
    }

    @Override
    public PgQuestionVo queryById(Long id) {
        PgQuestionVo pgQuestionVo = this.baseMapper.queryById(id);
        if (ObjectUtil.isNotEmpty(pgQuestionVo.getContent())) {
            pgQuestionVo.setOptionList(Arrays.asList(pgQuestionVo.getContent().split(",")));
        }
        return pgQuestionVo;
    }

    @Override
    public PgQuestionVo queryByTempId(Long tempId) {
        return baseMapper.queryByTempId(tempId);
    }

    @Override
    public Integer countByTempId(Long tempId) {
        return baseMapper.selectCountByTempId(tempId);
    }
}
